#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

double regionValue( Mat img, int x, int y, int dx, int dy ){
	double value = 0;
	Vec3b color;

	for (int i = x; i < x+dx; ++i){
		for (int j = y; j < y+dy; ++j){
			color = img.at<Vec3b>(j, i);
			value += color[0] + color[1] + color[2];
		}
	}

	return value/((double) (dx*dy));
}

int main( int argc, char** argv ){
	Mat image;
	int dx, dy;
	double minRegionValue = 1000;
	int w, h;
	double tmp;
	int xF, yF;
	int wantedValue = 255;

	if( argc != 4 ){
		cout << "Usage : ./DisplayImage ims dx dy" << endl;
		exit(0);
	}

	image = imread( argv[1], 1 );
	dx = atoi(argv[2]);
	dy = atoi(argv[2]);

	if( !image.data ){
		cout << "No image data" << endl;
		return -1;
	}

	h = image.size().height;
	w = image.size().width;

	namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );

	for (int x = 0; x < w-dx; x = x + 2){
		for (int y = 0; y < h-dy; y = y + 2){
			tmp = abs(regionValue( image, x, y, dx, dy ) - wantedValue);
			if(minRegionValue > tmp){
				minRegionValue = tmp;
				xF = x; yF = y;
			}
		}
	}

	cout << minRegionValue << " at : " << xF << "," << yF << endl;

	rectangle( image,
	           Point( xF, yF ),
	           Point( xF+dx, yF+dy),
	           Scalar( 0, 255, 0 ),
	           2,
	           8 );


	imshow( "Display Image", image );

	waitKey(0);

	return 0;
}